<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>{{ postName }}</span>
        <div style="float: right;" v-if="postCode">
          <el-button type="primary" size="small" icon="el-icon-refresh" @click="handleRefresh">刷新</el-button>
          <el-button type="success" size="small" icon="el-icon-check" @click="handleSave">保存</el-button>
          <el-button type="info" size="small" icon="el-icon-download" @click="handleExport">导出</el-button>
          <!-- <el-button type="warning" size="small" icon="el-icon-upload2" @click="handleImport">导入</el-button> -->
        </div>
      </div>

      <!-- 无模板提示 -->
      <div v-if="showNoTemplateWarning" style="text-align: center; padding: 100px 0; color: #E6A23C">
        <i class="el-icon-warning" style="font-size: 48px"></i>
        <p style="margin-top: 20px; font-size: 14px; margin-bottom: 20px">该岗位还未设置模板，请先设置模板数据</p>
        <el-button type="primary" icon="el-icon-setting" @click="goToTemplateManage">
          前往模板设置
        </el-button>
      </div>

      <!-- SpreadJS表格 -->
      <div v-else v-loading="loading" style="height: calc(100vh - 180px);">
        <spread-js
          ref="spreadjs"
          :key="spreadjsKey"
          :columns="columns"
          :data="tableData"
          :readonly="readonly"
          :use-designer="true"
          :header-readonly="true"
          :enforce-column-permissions="true"
          :container-id="spreadjsId"
          :enable-pagination="true"
          :page-size="100"
          @ready="handleSpreadJSReady"
          @load-more="handleLoadMore"
          @sheet-changed="handleSheetChanged"
          @save-shortcut="handleSave"
          @refresh-shortcut="handleRefresh"
        />
      </div>
    </el-card>

    <!-- 导入对话框 -->
    <el-dialog title="导入Excel" :visible.sync="importDialogVisible" width="400px" append-to-body>
      <el-upload
        class="upload-demo"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        accept=".xlsx,.xls"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmImport">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SpreadJS from '@/components/SpreadJS/index.vue'
import { getTalentData, saveTalentData, getRecruitmentStatusDict } from '@/api/talent/data'

export default {
  name: 'TalentPoolPage',
  components: {
    'spread-js': SpreadJS
  },
  data() {
    return {
      // 岗位信息（从路由参数获取）
      postCode: '',
      postName: '人才库数据维护',
      
      // SpreadJS相关
      spreadjsKey: 1,
      spreadjsId: 'talent-poolpage-spreadjs-' + Date.now(),
      spreadjsReady: false,
      pendingPaginationData: null,
      
      // 数据相关
      loading: false,
      columns: [],
      tableData: [],
      templateInfo: null,
      readonly: false,
      showNoTemplateWarning: false,
      
      // 多sheet相关
      availableSheets: [],
      currentSheetName: null,
      sheetsInitialized: false, // 标记sheet是否已初始化
      
      // 导入相关
      importDialogVisible: false,
      fileList: [],
      importFile: null
    }
  },
  created() {
    // 从路由参数获取 postCode
    this.postCode = this.$route.query.postCode || ''
    
    if (this.postCode) {
      this.loadData()
    } else {
      this.$modal.msgError('缺少岗位编码参数')
    }
  },
  methods: {
    /** 加载数据（支持分页和sheet切换） */
    loadData(page = 1, pageSize = 100, sheetName = null) {
      if (!this.postCode) return

      // 如果是第一次加载且没有初始化sheets，需要先检查是否需要初始化
      if (!this.sheetsInitialized && !sheetName) {
        this.initializeSheets(page, pageSize)
        return
      }

      // 正常加载数据
      this.loadSheetData(page, pageSize, sheetName)
    },

    /** 初始化sheet标签页 */
    initializeSheets(page = 1, pageSize = 100) {
      console.log('[TalentPoolPage] 开始初始化sheets')
      this.loading = true

      // 先获取模板字段信息，检查是否有招聘状态字段
      getTalentData(this.postCode, 1, 1).then(response => {
        const result = response.data
        
        // 转换字段配置
        this.columns = result.fields.map(field => {
          const columnWidth = field.columnWidth || 120
          console.log(`[TalentPoolPage] 字段 "${field.fieldLabel}" 后端宽度: ${field.columnWidth}, 最终宽度: ${columnWidth}`)
          return {
            fieldName: field.fieldName,
            fieldLabel: field.fieldLabel,
            fieldType: field.fieldType,
            cellTypeConfig: field.cellTypeConfig,
            sortOrder: field.sortOrder,
            isRequired: field.isRequired,
            permissionType: field.permissionType,
            readonly: field.permissionType === '0',
            width: columnWidth
          }
        })

        this.templateInfo = result.template
        this.readonly = !result.fields.some(f => f.permissionType === '1')

        // 设置页面标题
        if (result.template && result.template.templateName) {
          this.postName = result.template.templateName + '人才库'
        }

        // 检查是否有招聘状态字段
        const hasRecruitmentStatus = result.fields.some(field => field.fieldLabel === '招聘状态')
        
        if (hasRecruitmentStatus) {
          console.log('[TalentPoolPage] 检测到招聘状态字段，查询字典初始化sheets')
          
          // 查询招聘状态字典
          getRecruitmentStatusDict().then(dictResponse => {
            const dictData = dictResponse.data
            
            if (dictData && dictData.length > 0) {
              // 根据字典初始化sheet数据
              this.availableSheets = dictData.map(item => ({
                name: item.dictLabel,
                value: item.dictValue
              }))
              
              // 设置默认当前sheet为第一个
              this.currentSheetName = this.availableSheets[0].name
              this.sheetsInitialized = true
              
              console.log('[TalentPoolPage] ✓ 获取到', this.availableSheets.length, '个sheets:', this.availableSheets.map(s => s.name))
              
              // 保存多sheet初始化数据，等SpreadJS ready后处理
              this.pendingPaginationData = {
                multiSheet: true,
                availableSheets: this.availableSheets,
                loadData: { page, pageSize, sheetName: this.currentSheetName }
              }
              
              // 如果SpreadJS已就绪，立即处理
              if (this.spreadjsReady && this.$refs.spreadjs) {
                console.log('[TalentPoolPage] SpreadJS已就绪，立即创建多sheet')
                this.$refs.spreadjs.initMultiSheet(this.availableSheets)
                // 注意：不在这里手动加载数据，因为initMultiSheet会自动触发sheet-changed事件
                this.pendingPaginationData = null
              } else {
                console.log('[TalentPoolPage] SpreadJS未就绪，等待ready事件')
              }
            } else {
              console.log('[TalentPoolPage] 字典数据为空，使用单sheet模式')
              this.initializeSingleSheet(page, pageSize)
            }
          }).catch(error => {
            console.error('[TalentPoolPage] 查询字典失败:', error)
            this.initializeSingleSheet(page, pageSize)
          })
        } else {
          console.log('[TalentPoolPage] 未检测到招聘状态字段，使用单sheet模式')
          this.initializeSingleSheet(page, pageSize)
        }
      }).catch(error => {
        console.warn('岗位模板数据加载失败:', error.msg || error)
        this.showNoTemplateWarning = true
        this.columns = []
        this.tableData = []
        this.loading = false
      })
    },

    /** 初始化单sheet模式 */
    initializeSingleSheet(page, pageSize) {
      this.availableSheets = []
      this.currentSheetName = null
      this.sheetsInitialized = true
      
      // 加载数据
      this.loadSheetData(page, pageSize, null)
    },

    /** 加载指定sheet的数据 */
    loadSheetData(page = 1, pageSize = 100, sheetName = null) {
      console.log('[TalentPoolPage] ========== 开始加载sheet数据 ==========')
      console.log('[TalentPoolPage] 参数 - page:', page, 'pageSize:', pageSize, 'sheetName:', sheetName)
      console.log('[TalentPoolPage] 岗位代码:', this.postCode)
      console.log('[TalentPoolPage] availableSheets数量:', this.availableSheets.length)
      
      if (!this.postCode) {
        console.error('[TalentPoolPage] 岗位代码为空，无法加载数据')
        return
      }
      
      this.loading = true
      
      getTalentData(this.postCode, page, pageSize, sheetName).then(response => {
        console.log('[TalentPoolPage] API响应成功:', response)
        const result = response.data
        
        console.log('[TalentPoolPage] 返回数据结构:')
        console.log('  - result.data数量:', result.data ? result.data.length : 'null')
        console.log('  - result.total:', result.total)
        console.log('  - result.fields数量:', result.fields ? result.fields.length : 'null')
        console.log('  - 多sheet模式:', this.availableSheets.length > 1)

        // 更新当前sheet名称
        if (sheetName) {
          this.currentSheetName = sheetName
          console.log('[TalentPoolPage] 更新当前sheet名称为:', this.currentSheetName)
        }

        // 统一数据处理
        this.tableData = result.data || []
        console.log('[TalentPoolPage] 处理后的tableData数量:', this.tableData.length)

        // 如果SpreadJS已就绪，立即更新当前sheet数据
        if (this.spreadjsReady && this.$refs.spreadjs) {
          console.log('[TalentPoolPage] SpreadJS已就绪，开始更新数据')
          
          if (this.availableSheets.length > 1) {
            // 多sheet模式：更新当前sheet的数据，传递total支持分页
            console.log('[TalentPoolPage] 使用多sheet模式更新数据，total:', result.total)
            this.$refs.spreadjs.updateCurrentSheetData(this.tableData, result.total || 0)
          } else {
            // 单sheet模式：使用原有的分页初始化
            console.log('[TalentPoolPage] 使用单sheet模式初始化数据，total:', result.total)
            this.$refs.spreadjs.initPaginationData(this.tableData, result.total || 0)
          }
          this.loading = false
          console.log('[TalentPoolPage] 数据更新完成，loading设为false')
        } else {
          console.log('[TalentPoolPage] SpreadJS未就绪，保存待初始化数据')
          // 保存待初始化的数据，等SpreadJS ready后处理
          this.pendingPaginationData = {
            data: this.tableData,
            total: result.total || 0
          }
        }
        
        console.log('[TalentPoolPage] ========== sheet数据加载完成 ==========')
      }).catch(error => {
        console.error('[TalentPoolPage] sheet数据加载失败:', error)
        console.error('[TalentPoolPage] 错误详情:', error.msg || error.message || error)
        this.loading = false
      })
    },

    /** SpreadJS组件就绪 */
    handleSpreadJSReady() {
      this.spreadjsReady = true
      
      console.log('[TalentPoolPage] SpreadJS组件就绪')
      console.log('[TalentPoolPage] 待处理数据:', this.pendingPaginationData)
      
      if (this.pendingPaginationData) {
        if (this.pendingPaginationData.multiSheet) {
          console.log('[TalentPoolPage] 处理多sheet初始化')
          this.$refs.spreadjs.initMultiSheet(this.pendingPaginationData.availableSheets)
          // 不在这里加载数据，initMultiSheet会触发sheet-changed事件
          this.pendingPaginationData = null
        } else {
          console.log('[TalentPoolPage] 处理单sheet分页数据')
          this.$refs.spreadjs.initPaginationData(this.pendingPaginationData.data, this.pendingPaginationData.total)
          this.pendingPaginationData = null
          this.loading = false
        }
      }
    },

    /** 处理Sheet切换事件 */
    handleSheetChanged(sheetName) {
      console.log('[TalentPoolPage] ==================== 处理Sheet切换 ====================')
      console.log('[TalentPoolPage] 收到sheet切换事件:', sheetName)
      console.log('[TalentPoolPage] 当前岗位代码:', this.postCode)
      console.log('[TalentPoolPage] SpreadJS就绪状态:', this.spreadjsReady)
      console.log('[TalentPoolPage] 可用sheets:', this.availableSheets)
      
      if (!this.postCode) {
        console.error('[TalentPoolPage] 岗位代码为空，无法加载数据')
        return
      }
      
      if (!this.spreadjsReady) {
        console.warn('[TalentPoolPage] SpreadJS未就绪，延迟处理')
        return
      }
      
      // 每次切换都重新加载数据（即使是同一个sheet，用户主动切换也应该刷新）
      console.log('[TalentPoolPage] 准备加载sheet数据，从', this.currentSheetName, '切换到', sheetName)
      
      // 重新加载指定sheet的数据
      console.log('[TalentPoolPage] 开始加载sheet数据:', sheetName)
      this.loadSheetData(1, 100, sheetName)
      console.log('[TalentPoolPage] ==================== Sheet切换处理完成 ====================')
    },

    /** 加载更多数据 */
    handleLoadMore(params) {
      const { page, pageSize, callback } = params
      
      // 在多sheet模式下，loadMore应该传递当前sheet名称
      const sheetName = this.availableSheets.length > 1 ? this.currentSheetName : null
      
      getTalentData(this.postCode, page, pageSize, sheetName).then(response => {
        const result = response.data
        // 调用回调函数，追加数据
        callback(result.data || [], result.total || 0)
      }).catch(() => {
        callback([], 0)
      })
    },

    /** 刷新 */
    handleRefresh() {
      // 保存当前sheet状态
      const currentSheetBeforeRefresh = this.currentSheetName
      console.log('[TalentPoolPage] 刷新前当前sheet:', currentSheetBeforeRefresh)
      
      // 根据是否为多sheet模式决定刷新策略
      if (this.availableSheets.length > 1 && currentSheetBeforeRefresh) {
        // 多sheet模式：只刷新当前sheet的数据，保持sheet状态
        console.log('[TalentPoolPage] 多sheet模式刷新，只刷新当前sheet:', currentSheetBeforeRefresh)
        this.loadSheetData(1, 100, currentSheetBeforeRefresh)
      } else {
        // 单sheet模式：使用原有的完整刷新逻辑（重置组件）
        console.log('[TalentPoolPage] 单sheet模式刷新，完整重置组件')
        this.spreadjsKey += 1
        this.spreadjsId = 'talent-poolpage-spreadjs-' + Date.now()
        this.spreadjsReady = false
        this.pendingPaginationData = null
        this.sheetsInitialized = false // 重置sheet初始化状态
        this.loadData()
      }
    },

    /** 保存 */
    handleSave() {
      if (this.readonly) {
        this.$modal.msgError('您没有修改权限')
        return
      }

      // 从SpreadJS获取数据
      const data = this.$refs.spreadjs.getData()

      // 保存当前sheet状态
      const currentSheetBeforeSave = this.currentSheetName
      console.log('[TalentPoolPage] 保存前当前sheet:', currentSheetBeforeSave)

      this.loading = true
      saveTalentData(this.postCode, data).then(response => {
        // 显示保存成功消息，包含快捷键提示
        this.$modal.msgSuccess('保存成功！快捷键提示：Ctrl+S 保存，F5 刷新')
        
        // 根据是否为多sheet模式决定刷新策略
        if (this.availableSheets.length > 1 && currentSheetBeforeSave) {
          // 多sheet模式：只刷新当前sheet的数据，保持sheet状态
          console.log('[TalentPoolPage] 多sheet模式保存成功，刷新当前sheet:', currentSheetBeforeSave)
          this.loadSheetData(1, 100, currentSheetBeforeSave)
        } else {
          // 单sheet模式：使用原有的刷新逻辑
          console.log('[TalentPoolPage] 单sheet模式保存成功，完整刷新')
          this.handleRefresh()
        }
      }).catch(() => {
        this.loading = false
      })
    },

    /** 导出 */
    handleExport() {
      const fileName = `${this.postName}_${new Date().getTime()}.xlsx`
      this.$refs.spreadjs.exportExcel(fileName)
    },

    /** 导入 */
    handleImport() {
      this.fileList = []
      this.importFile = null
      this.importDialogVisible = true
    },

    /** 文件变化 */
    handleFileChange(file) {
      this.importFile = file.raw
    },

    /** 确认导入 */
    confirmImport() {
      if (!this.importFile) {
        this.$modal.msgError('请选择文件')
        return
      }

      this.$refs.spreadjs.importExcel(this.importFile)
      this.importDialogVisible = false
    },

    /** 跳转到模板管理 */
    goToTemplateManage() {
      // 跳转到人才库模板管理页面
      this.$router.push('/talent/template')
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>


